Page({
  data: {
    board: [],
    score: 0,
    timeLeft: 120,
    timeLeftFormatted: '2:00',
    selectedTile: null,
    icons: [
      '/static/TwemojiTulip.svg',
      '/static/TwemojiTeddyBear.svg',
      '/static/TwemojiSunflower.svg',
      '/static/TwemojiRibbon.svg',
      '/static/TwemojiPigFace.svg',
      '/static/TwemojiMushroom.svg',
      '/static/TwemojiMango.svg',
      '/static/TwemojiLotionBottle.svg'
    ],
    tileSize: 0,
    screenWidth: 0,
    screenHeight: 0,
    currentLevel: 1,
    bombCount: 3,
    hintCount: 3,
    shuffleCount: 1,
    isSettingsVisible: false,
    isPaused: false
  },

  onLoad() {
    // 获取屏幕尺寸
    const systemInfo = wx.getSystemInfoSync();
    const tileSize = Math.floor(systemInfo.windowWidth / 9); // 动态计算方块大小
    
    this.setData({
      tileSize: tileSize,
      screenWidth: systemInfo.windowWidth,
      screenHeight: systemInfo.windowHeight,
      currentLevel: 1, // 初始关卡设为1
      bombCount: 3, // 初始炸弹数量
      hintCount: 3, // 初始提示数量
      shuffleCount: 1 // 初始洗牌数量
    });
    
    this.initGame();
    this.startTimer();
  },

  initGame() {
    const board = [];
    const rows = 11;
    const cols = 8;
    
    // 生成配对的图标数组
    let tiles = [];
    for (let i = 0; i < (rows * cols) / 2; i++) {
      const iconIndex = i % this.data.icons.length;
      tiles.push({
        value: 1,
        icon: this.data.icons[iconIndex],
        selected: false,
        matched: false
      });
      tiles.push({
        value: 1,
        icon: this.data.icons[iconIndex],
        selected: false,
        matched: false
      });
    }
    
    // 如果总数是奇数，需要添加一个空白方块
    if ((rows * cols) % 2 !== 0) {
      tiles.push({
        value: 0,
        icon: '',
        selected: false,
        matched: false
      });
    }
    
    // 随机打乱
    tiles = this.shuffle(tiles);
    
    // 填充板子
    for (let i = 0; i < rows; i++) {
      const row = [];
      for (let j = 0; j < cols; j++) {
        const index = i * cols + j;
        if (index < tiles.length) {
          const tile = tiles[index];
          tile.row = i;
          tile.col = j;
          row.push(tile);
        } else {
          // 防止越界，添加空白方块
          row.push({
            value: 0,
            icon: '',
            selected: false,
            matched: false,
            row: i,
            col: j
          });
        }
      }
      board.push(row);
    }
    
    console.log('初始化后的棋盘:', board);
    
    // 如果没有传入currentLevel，则保持不变或设为1
    const currentLevel = this.data.currentLevel || 1;
    
    this.setData({
      board,
      score: 0,
      selectedTile: null,
      currentLevel: currentLevel,
      bombCount: 3,
      hintCount: 3,
      shuffleCount: 1
    });
  },

  shuffle(array) {
    let currentIndex = array.length;
    while (currentIndex !== 0) {
      const randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex--;
      [array[currentIndex], array[randomIndex]] = [array[randomIndex], array[currentIndex]];
    }
    return array;
  },

  startTimer() {
    // 如果游戏暂停中，不启动计时器
    if (this.data.isPaused) {
      return;
    }

    // 先清除已存在的定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
    
    // 启动新的定时器
    this.timer = setInterval(() => {
      if (this.data.timeLeft <= 0) {
        this.gameOver();
        return;
      }
      
      const newTimeLeft = this.data.timeLeft - 1;
      
      // 格式化时间为 分:秒 格式
      const minutes = Math.floor(newTimeLeft / 60);
      const seconds = newTimeLeft % 60;
      const formattedTime = `${minutes}:${seconds < 10 ? '0' + seconds : seconds}`;
      
      this.setData({
        timeLeft: newTimeLeft,
        timeLeftFormatted: formattedTime
      });
    }, 1000);
  },

  onTileTap(e) {
    const { row, col } = e.currentTarget.dataset;
    console.log('点击坐标 - row:', row, 'col:', col);
    
    if (typeof row === 'undefined' || typeof col === 'undefined') {
      console.error('坐标未定义 - row:', row, 'col:', col);
      return;
    }

    const board = JSON.parse(JSON.stringify(this.data.board));
    const currentTile = board[row][col];

    if (!currentTile || currentTile.value !== 1) {
      console.log('方块无效或已被消除');
      return;
    }

    if (!this.data.selectedTile) {
      // 第一次选择
      currentTile.selected = true;
      
      this.setData({
        board,
        selectedTile: { row, col }
      });
    } else {
      // 第二次选择
      const firstTile = this.data.selectedTile;
      
      if (firstTile.row === row && firstTile.col === col) {
        board[row][col].selected = false;
        this.setData({
          board,
          selectedTile: null
        });
        return;
      }

      // 检查是否可以连接
      if (this.canConnect(firstTile, { row, col })) {
        board[firstTile.row][firstTile.col].matched = true;
        board[row][col].matched = true;
        
        this.setData({ board }, () => {
          setTimeout(() => {
            board[firstTile.row][firstTile.col].value = 0;
            board[row][col].value = 0;
            
            this.setData({
              board,
              score: this.data.score + 10,
              selectedTile: null
            }, () => {
              this.checkGameComplete();
            });
          }, 300);
        });
      } else {
        // 匹配失败
        board[firstTile.row][firstTile.col].selected = false;
        this.setData({
          board,
          selectedTile: null
        });
      }
    }
  },

  // 检查两个方块是否可以连接
  canConnect(tile1, tile2) {
    const { row: row1, col: col1 } = tile1;
    const { row: row2, col: col2 } = tile2;
    const board = this.data.board;

    // 检查是否点击同一个方块
    if (row1 === row2 && col1 === col2) {
      return false;
    }

    // 检查两个方块是否相同类型
    if (board[row1][col1].icon !== board[row2][col2].icon) {
      return false;
    }

    // 检查是否都在边界上
    const isOnBorder = this.isOnBorder(row1, col1, row2, col2);
    if (isOnBorder) {
      return true;
    }

    // 如果不在边界上，使用原有的连接检查逻辑
    // 直接路径检测
    if (this.checkDirectPath(row1, col1, row2, col2)) {
      return true;
    }

    // 一次转弯检测
    const oneCornerPath = this.checkOneCornerPath(row1, col1, row2, col2);
    if (oneCornerPath) {
      return true;
    }

    // 两次转弯检测
    const twoCornerPath = this.checkTwoCornerPath(row1, col1, row2, col2);
    if (twoCornerPath) {
      return true;
    }

    return false;
  },

  // 新增：检查两个方块是否都在边界上
  isOnBorder(row1, col1, row2, col2) {
    const rows = this.data.board.length;
    const cols = this.data.board[0].length;

    // 检查是否至少有一个方块在边界上
    const tile1OnBorder = row1 === 0 || row1 === rows - 1 || col1 === 0 || col1 === cols - 1;
    const tile2OnBorder = row2 === 0 || row2 === rows - 1 || col2 === 0 || col2 === cols - 1;

    // 检查是否在同一边界上
    if (tile1OnBorder && tile2OnBorder) {
      // 在同一行的最上边或最下边
      if ((row1 === 0 && row2 === 0) || (row1 === rows - 1 && row2 === rows - 1)) {
        return true;
      }
      // 在同一列的最左边或最右边
      if ((col1 === 0 && col2 === 0) || (col1 === cols - 1 && col2 === cols - 1)) {
        return true;
      }
      // 在相邻的边界上（形成一个拐角）
      if ((row1 === 0 || row1 === rows - 1) && (col2 === 0 || col2 === cols - 1)) {
        return true;
      }
      if ((row2 === 0 || row2 === rows - 1) && (col1 === 0 || col1 === cols - 1)) {
        return true;
      }
    }

    return false;
  },

  // 检查直线路径
  checkDirectPath(row1, col1, row2, col2) {
    // 如果不在同一行或同一列，返回false
    if (row1 !== row2 && col1 !== col2) {
      return false;
    }

    // 检查水平方向
    if (row1 === row2) {
      const minCol = Math.min(col1, col2);
      const maxCol = Math.max(col1, col2);
      // 检查两点之间是否有障碍物
      for (let col = minCol + 1; col < maxCol; col++) {
        if (this.data.board[row1][col].value !== 0) {
          return false;
        }
      }
      return true;
    }

    // 检查垂直方向
    if (col1 === col2) {
      const minRow = Math.min(row1, row2);
      const maxRow = Math.max(row1, row2);
      // 检查两点之间是否有障碍物
      for (let row = minRow + 1; row < maxRow; row++) {
        if (this.data.board[row][col1].value !== 0) {
          return false;
        }
      }
      return true;
    }
  },

  // 检查一次转弯路径
  checkOneCornerPath(row1, col1, row2, col2) {
    // 检查两个转折点
    const cornerPoints = [
      { row: row1, col: col2 }, // 转折点1
      { row: row2, col: col1 }  // 转折点2
    ];

    for (const corner of cornerPoints) {
      // 检查转折点是否为空
      if (this.data.board[corner.row][corner.col].value !== 0) {
        continue;
      }

      // 检查两段直线路径
      if (this.checkDirectPath(row1, col1, corner.row, corner.col) &&
          this.checkDirectPath(corner.row, corner.col, row2, col2)) {
        return true;
      }
    }

    return false;
  },

  // 检查两次转弯路径
  checkTwoCornerPath(row1, col1, row2, col2) {
    const board = this.data.board;
    const rows = board.length;
    const cols = board[0].length;

    // 遍历所有可能的中间点
    for (let row = 0; row < rows; row++) {
      for (let col = 0; col < cols; col++) {
        // 跳过非空位置
        if (board[row][col].value !== 0) {
          continue;
        }

        // 检查第一个转折点到起点
        if (this.checkDirectPath(row1, col1, row, col)) {
          // 尝试两种可能的第二个转折点
          const corner1 = { row: row, col: col2 };
          const corner2 = { row: row2, col: col };

          // 检查第一种可能的两次转弯路径
          if (board[corner1.row][corner1.col].value === 0 &&
              this.checkDirectPath(row, col, corner1.row, corner1.col) &&
              this.checkDirectPath(corner1.row, corner1.col, row2, col2)) {
            return true;
          }

          // 检查第二种可能的两次转弯路径
          if (board[corner2.row][corner2.col].value === 0 &&
              this.checkDirectPath(row, col, corner2.row, corner2.col) &&
              this.checkDirectPath(corner2.row, corner2.col, row2, col2)) {
            return true;
          }
        }
      }
    }

    return false;
  },

  // 检查游戏是否完成
  checkGameComplete() {
    const board = this.data.board;
    let hasRemaining = false;

    for (let row of board) {
      for (let cell of row) {
        if (cell.value !== 0) {
          hasRemaining = true;
          break;
        }
      }
      if (hasRemaining) break;
    }

    if (!hasRemaining) {
      // 游戏胜利
      clearInterval(this.timer);
      
      // 计算额外时间奖励
      const timeBonus = Math.floor(this.data.timeLeft * 0.5);
      const finalScore = this.data.score + timeBonus;

      wx.showModal({
        title: '恭喜通关！',
        content: `最终得分：${finalScore}\n时间奖励：${timeBonus}`,
        confirmText: '下一关',
        cancelText: '返回主页',
        success: (res) => {
          if (res.confirm) {
            // 保存分数并进入下一关
            this.saveHighScore(finalScore);
            this.goToNextLevel();
          } else {
            // 保存分数并返回主页
            this.saveHighScore(finalScore);
            wx.navigateBack();
          }
        }
      });
    }
  },

  // 保存最高分
  saveHighScore(score) {
    const highScore = wx.getStorageSync('highScore') || 0;
    if (score > highScore) {
      wx.setStorageSync('highScore', score);
    }
  },

  gameOver() {
    clearInterval(this.timer);
    
    wx.showModal({
      title: '游戏结束',
      content: `最终得分：${this.data.score}`,
      confirmText: '重新开始',
      cancelText: '返回主页',
      success: (res) => {
        if (res.confirm) {
          // 重新开始当前关卡
          this.restartGame();
        } else {
          // 返回主页
          wx.navigateBack();
        }
      }
    });
  },

  onUnload() {
    clearInterval(this.timer);
  },

  // 添加清除所有选中状态的方法
  clearAllSelected(board) {
    for (let row of board) {
      for (let cell of row) {
        if (cell) {
          cell.selected = false;
          cell.matched = false;
        }
      }
    }
  },

  // 添加重新开始游戏方法
  restartGame() {
    // 先清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
    
    // 重置时间
    this.setData({
      timeLeft: 120,
      timeLeftFormatted: '2:00'
    }, () => {
      // 在状态更新完成后再初始化游戏和启动定时器
      this.initGame();
      this.startTimer();
    });
  },

  // 添加返回主页方法
  backToHome() {
    wx.showModal({
      title: '提示',
      content: '确定要退出当前游戏吗？',
      success: (res) => {
        if (res.confirm) {
          clearInterval(this.timer);
          wx.navigateBack();
        }
      }
    });
  },

  // 添加进入下一关的方法
  goToNextLevel() {
    // 先清除当前定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
    
    // 获取当前关卡
    const currentLevel = this.data.currentLevel || 1;
    
    // 设置下一关的关卡和重置时间
    this.setData({
      currentLevel: currentLevel + 1,
      timeLeft: 120,
      timeLeftFormatted: '2:00'
    }, () => {
      // 在状态更新完成后再初始化游戏和启动定时器
      this.initGame();
      this.startTimer();
    });
  },

  // 使用炸弹道具，自动消除一组相同的方块
  useBomb() {
    // 检查炸弹数量
    if (this.data.bombCount <= 0) {
      wx.showToast({
        title: '炸弹数量不足',
        icon: 'none'
      });
      return;
    }

    // 在棋盘上寻找可以消除的一组
    let foundPair = this.findMatchingPair();
    
    if (foundPair) {
      const { tile1, tile2 } = foundPair;
      const board = JSON.parse(JSON.stringify(this.data.board));
      
      // 高亮显示要消除的方块
      board[tile1.row][tile1.col].matched = true;
      board[tile2.row][tile2.col].matched = true;
      
      this.setData({ board }, () => {
        // 延时后消除方块
        setTimeout(() => {
          board[tile1.row][tile1.col].value = 0;
          board[tile2.row][tile2.col].value = 0;
          
          this.setData({
            board,
            score: this.data.score + 5, // 使用道具获得的分数较少
            bombCount: this.data.bombCount - 1 // 减少炸弹数量
          }, () => {
            this.checkGameComplete();
          });
        }, 300);
      });
    } else {
      wx.showToast({
        title: '没有可消除的方块',
        icon: 'none'
      });
    }
  },

  // 使用提示道具，高亮显示一组可消除的方块
  useHint() {
    // 检查提示数量
    if (this.data.hintCount <= 0) {
      wx.showToast({
        title: '提示数量不足',
        icon: 'none'
      });
      return;
    }

    // 在棋盘上寻找可以消除的一组
    let foundPair = this.findMatchingPair();
    
    if (foundPair) {
      const { tile1, tile2 } = foundPair;
      const board = JSON.parse(JSON.stringify(this.data.board));
      
      // 高亮显示提示的方块（使用hinted标记）
      board[tile1.row][tile1.col].hinted = true;
      board[tile2.row][tile2.col].hinted = true;
      
      this.setData({
        board,
        hintCount: this.data.hintCount - 1 // 减少提示数量
      });
      
      // 3秒后取消高亮
      setTimeout(() => {
        const currentBoard = JSON.parse(JSON.stringify(this.data.board));
        if (currentBoard[tile1.row][tile1.col].value !== 0) {
          currentBoard[tile1.row][tile1.col].hinted = false;
        }
        if (currentBoard[tile2.row][tile2.col].value !== 0) {
          currentBoard[tile2.row][tile2.col].hinted = false;
        }
        this.setData({ board: currentBoard });
      }, 3000);
    } else {
      wx.showToast({
        title: '没有可消除的方块',
        icon: 'none'
      });
    }
  },

  // 洗牌功能，重新打乱剩余的方块
  shuffleBoard() {
    // 检查洗牌次数
    if (this.data.shuffleCount <= 0) {
      wx.showToast({
        title: '洗牌次数不足',
        icon: 'none'
      });
      return;
    }

    // 收集所有未消除的方块
    let remainingTiles = [];
    const board = JSON.parse(JSON.stringify(this.data.board));
    
    // 先收集所有有效方块
    for (let i = 0; i < board.length; i++) {
      for (let j = 0; j < board[i].length; j++) {
        if (board[i][j].value !== 0) {
          remainingTiles.push({
            value: board[i][j].value,
            icon: board[i][j].icon,
            selected: false,
            matched: false,
            hinted: false
          });
          // 清空原位置
          board[i][j].value = 0;
          board[i][j].icon = '';
          board[i][j].selected = false;
          board[i][j].matched = false;
          board[i][j].hinted = false;
        }
      }
    }
    
    // 如果没有剩余方块，直接返回
    if (remainingTiles.length === 0) {
      wx.showToast({
        title: '没有可洗牌的方块',
        icon: 'none'
      });
      return;
    }
    
    // 洗牌
    remainingTiles = this.shuffle(remainingTiles);
    
    // 创建有效位置列表（所有空位置）
    let validPositions = [];
    for (let i = 0; i < board.length; i++) {
      for (let j = 0; j < board[i].length; j++) {
        validPositions.push({row: i, col: j});
      }
    }
    
    // 随机选择validPositions中的位置放置方块
    validPositions = this.shuffle(validPositions);
    
    // 重新放回棋盘 - 确保不会超出方块数量
    for (let i = 0; i < Math.min(remainingTiles.length, validPositions.length); i++) {
      const pos = validPositions[i];
      const tile = remainingTiles[i];
      
      board[pos.row][pos.col].value = tile.value;
      board[pos.row][pos.col].icon = tile.icon;
      board[pos.row][pos.col].selected = false;
      board[pos.row][pos.col].matched = false;
      board[pos.row][pos.col].hinted = false;
      board[pos.row][pos.col].row = pos.row;
      board[pos.row][pos.col].col = pos.col;
    }
    
    // 减少洗牌次数
    this.setData({
      board,
      selectedTile: null,
      shuffleCount: this.data.shuffleCount - 1
    });
    
   
    // 增加一个检查，确认洗牌后还能配对
    setTimeout(() => {
      const hasPair = this.findMatchingPair();
      if (!hasPair) {
        wx.showToast({
          title: '没有可匹配的方块，再次洗牌',
          icon: 'none',
          duration: 1500
        });
        
        // 延迟一下再次洗牌，让用户看到提示
        setTimeout(() => {
          // 不消耗洗牌次数的额外洗牌
          this.autoReshuffleBoard();
        }, 1500);
      }
    }, 500);
  },

  // 自动重新洗牌（不消耗洗牌次数）
  autoReshuffleBoard() {
    // 收集所有未消除的方块
    let remainingTiles = [];
    const board = JSON.parse(JSON.stringify(this.data.board));
    
    // 先收集所有有效方块
    for (let i = 0; i < board.length; i++) {
      for (let j = 0; j < board[i].length; j++) {
        if (board[i][j].value !== 0) {
          remainingTiles.push({
            value: board[i][j].value,
            icon: board[i][j].icon,
            selected: false,
            matched: false,
            hinted: false
          });
          // 清空原位置
          board[i][j].value = 0;
          board[i][j].icon = '';
          board[i][j].selected = false;
          board[i][j].matched = false;
          board[i][j].hinted = false;
        }
      }
    }
    
    // 如果没有剩余方块，直接返回
    if (remainingTiles.length === 0) {
      return;
    }
    
    // 洗牌
    remainingTiles = this.shuffle(remainingTiles);
    
    // 创建有效位置列表
    let validPositions = [];
    for (let i = 0; i < board.length; i++) {
      for (let j = 0; j < board[i].length; j++) {
        validPositions.push({row: i, col: j});
      }
    }
    
    // 随机选择validPositions中的位置放置方块
    validPositions = this.shuffle(validPositions);
    
    // 重新放回棋盘
    for (let i = 0; i < Math.min(remainingTiles.length, validPositions.length); i++) {
      const pos = validPositions[i];
      const tile = remainingTiles[i];
      
      board[pos.row][pos.col].value = tile.value;
      board[pos.row][pos.col].icon = tile.icon;
      board[pos.row][pos.col].selected = false;
      board[pos.row][pos.col].matched = false;
      board[pos.row][pos.col].hinted = false;
      board[pos.row][pos.col].row = pos.row;
      board[pos.row][pos.col].col = pos.col;
    }
    
    this.setData({
      board,
      selectedTile: null
    });
    
    wx.showToast({
      title: '已重新洗牌',
      icon: 'success'
    });
  },

  // 寻找一组可以消除的方块
  findMatchingPair() {
    const board = this.data.board;
    const rows = board.length;
    const cols = board[0].length;
    
    // 创建索引映射，按图标类型分组
    const iconGroups = {};
    
    // 遍历棋盘收集所有方块
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < cols; j++) {
        const tile = board[i][j];
        if (tile.value !== 0) {
          if (!iconGroups[tile.icon]) {
            iconGroups[tile.icon] = [];
          }
          iconGroups[tile.icon].push({
            row: i,
            col: j,
            icon: tile.icon
          });
        }
      }
    }
    
    // 遍历所有图标组，找到可以连接的一对
    for (const icon in iconGroups) {
      const group = iconGroups[icon];
      if (group.length >= 2) {
        // 检查每一对方块是否可以连接
        for (let i = 0; i < group.length; i++) {
          for (let j = i + 1; j < group.length; j++) {
            const tile1 = group[i];
            const tile2 = group[j];
            
            // 使用现有的canConnect方法检查是否可以连接
            if (this.canConnect(tile1, tile2)) {
              return { tile1, tile2 };
            }
          }
        }
      }
    }
    
    return null;
  },

  // 显示设置弹窗
  showSettings() {
    // 暂停计时器
    if (this.timer) {
      clearInterval(this.timer);
    }
    
    this.setData({
      isSettingsVisible: true,
      isPaused: true
    });
  },

  // 继续游戏
  continueGame() {
    this.setData({
      isSettingsVisible: false,
      isPaused: false
    }, () => {
      // 直接重新启动计时器，不需要检查timer是否存在
      if (this.data.timeLeft > 0) {
        this.startTimer();
      }
    });
  },

  // 显示广告并重新开始
  showAd() {
    // 创建广告实例
    if (!this.videoAd) {
      this.videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-2c79371935180555'
      });

      this.videoAd.onError(err => {
        console.log('广告加载失败', err);
        // 广告失败也允许重新开始
        this.restartAfterAd();
      });

      this.videoAd.onClose(res => {
        if (res && res.isEnded) {
          // 正常播放结束，重新开始游戏
          this.restartAfterAd();
        } else {
          // 播放中途退出，不做处理
          wx.showToast({
            title: '需要看完广告才能重新开始',
            icon: 'none'
          });
        }
      });
    }

    // 显示广告
    this.videoAd.show().catch(() => {
      // 失败重试
      this.videoAd.load()
        .then(() => this.videoAd.show())
        .catch(err => {
          console.log('广告显示失败', err);
          // 广告失败也允许重新开始
          this.restartAfterAd();
        });
    });
  },

  // 广告结束后重新开始
  restartAfterAd() {
    this.setData({
      isSettingsVisible: false,
      isPaused: false,
      score: 0,
      timeLeft: 120,
      timeLeftFormatted: '2:00',
      bombCount: 3,
      hintCount: 3,
      shuffleCount: 1
    }, () => {
      this.initGame();
      this.startTimer();
    });
  }
}); 